package producter

import (
	"github.com/streadway/amqp"
	"log"
)

func failOnError(err error, msg string) {
	if err != nil {
		log.Fatalf("%s: %s", msg, err)
	}
}

//host "amqp://admin:admin@192.168.10.138:5672/"
func Producter(host string, exchangeName string, routing string, msg string) {
	conn, err := amqp.Dial(host)
	failOnError(err, "Failed to connect to RabbitMQ")
	defer conn.Close()

	//创建一个channel来传递消息
	ch, err := conn.Channel()
	failOnError(err, "Failed to open a channel")
	defer ch.Close()

	// 声明一个交换机
	err = ch.ExchangeDeclare(
		exchangeName, // name  交换机名称
		"topic",      // type  主题交换机
		true,         // durable 持久化
		false,        // auto-deleted
		false,        // internal
		false,        // no-wait
		nil,          // arguments
	)
	failOnError(err, "Failed to declare an exchange")

	// 发送消息
	err = ch.Publish(
		exchangeName, // exchange
		routing,      // routing key
		false,        // mandatory
		false,        // immediate
		amqp.Publishing{
			ContentType: "text/plain",
			Body:        []byte(msg),
		})
	failOnError(err, "Failed to publish a message")
	log.Printf("Sent to exchange %s with routing key %s , msg: %s",
		exchangeName, routing, msg)
}
